<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" style="margin-bottom:20px">
      <span style="margin-left:10px">高中名称：</span>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输入高中名称" v-model="listQuery.title" clearable></el-input>

      <span style="margin-left:10px">所属地区：</span>
      <el-cascader class="search__input" change-on-select clearable placeholder="全部" expand-trigger="click" :options="areaCascadeOptions" v-model="listQuery.areaId" />

      <span style="margin-left:10px">是否开通高中后台系统：</span>
      <el-select v-model="listQuery.isSchoolManage" placeholder="请选择" style="width: 100px;" clearable>
        <el-option v-for="manage in isSchoolManageList" :key="manage.id" :label="manage.name" :value="manage.type"></el-option>
      </el-select>

      <span style="margin-left:10px">是否开通高中PC端生涯测评系统：</span>
      <el-select v-model="listQuery.isSchoolPcReport" placeholder="请选择" style="width: 100px;" clearable>
        <el-option v-for="pc in isSchoolPcReportList" :key="pc.id" :label="pc.name" :value="pc.type"></el-option>
      </el-select>

      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <!-- <el-button class="filter-item addAcademy"  type="success" icon="el-icon-plus" @click="addAcademy">新增高中</el-button> -->
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="数据加载中，请稍后" border fit highlight-current-row style="width: 100%">
      <el-table-column v-if='showAllDel' type="selection" width="55" />
      <el-table-column min-width="80" align="center" label="高中ID" prop="id" />
      <el-table-column min-width="150" align="center" label="高中名称" prop="title" />  
      <el-table-column min-width="150" align="center" label="所属地区" prop="areaNames" />
      <!-- <el-table-column min-width="120" align="center" label="注册时间" show-overflow-tooltip> -->
      <el-table-column min-width="120" align="center" label="注册教师人数" prop="teacherNum" />
      <el-table-column align="center" prop="isSchoolManage" label="是否开通高中后台系统" min-width="150">
        <template slot-scope="scope"> {{scope.row.isSchoolManage == 1 ? '是' : '否' }} </template>
      </el-table-column>
      <el-table-column align="center" prop="isSchoolPcReport" label="是否开通高中PC端生涯测评系统" min-width="180">
        <template slot-scope="scope"> {{scope.row.isSchoolPcReport == 1 ? '是' : '否' }} </template>
      </el-table-column>
      <el-table-column align="center" label="高中后台系统操作" show-overflow-tooltip min-width="200">
        <template slot-scope="scope">
          <el-button size="small" type="primary" v-if="scope.row.isSchoolManage==0" @click="open(scope.row)">开通</el-button>
          <el-button size="small" type="primary" v-if="scope.row.isSchoolManage==1" @click="update(scope.row)">编辑</el-button>
          <el-button size="small" type="primary" v-if="scope.row.isSchoolManage==1" @click="handleClose(scope.row)">关闭</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="高中PC端生涯测评系统操作" show-overflow-tooltip min-width="200">
        <template slot-scope="scope">
          <el-button size="small" type="primary" v-if="scope.row.isSchoolPcReport==0" @click="handleOpenPC(scope.row)">开通</el-button>
          <el-button size="small" type="primary" v-if="scope.row.isSchoolPcReport==1" @click="handleClosePC(scope.row)">关闭</el-button>
        </template>
      </el-table-column>
        <!-- <template slot-scope="scope"> -->
          <!-- <span>{{scope.row.createTime | dateformat('YYYY-MM-DD HH:mm')}}</span> -->
          <!-- <span>{{scope.row.createTime | dateformat('YYYY-MM-DD')}}</span>
        </template> -->
    </el-table>
    <!-- 分页 -->
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo" :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 弹窗 -->
    <el-dialog title="开通信息：" :visible.sync="dialogVisible" width="40%" center>
      <el-form >
        <el-form-item label="手机号（必填）" label-width="80px">
          <el-input v-model="mob" placeholder="请输入11位电话号码" maxlength='11' style="width: 200px;"></el-input>
          <span style="color:red;">{{msgMobile}}</span>
        </el-form-item>

        <el-form-item label="密码（必填）" label-width="80px">
          <el-input type="password" v-model="pass" auto-complete="new-password" placeholder="请输入6-18位密码" maxlength='18' minlength="6" style="width: 200px;"></el-input> 
          <span style="color:red;">{{msgPassword}}</span> 
        </el-form-item>

        <el-form-item label-width="100px" label="设置开通权限：" class="postInfo-container-item">
          <el-select v-model="permission" multiple placeholder="请选择（可多选）" @change="getPermissionOptions" track-by="value" label="label">
            <el-option
              v-for="item in conditions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleOpen()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑用户信息：" :visible.sync="dialogUserInfoVisible" width="40%" center>
      <el-form >
        <el-form-item label="手机号（必填）" label-width="80px">
          <el-input v-model="mobile" placeholder="请输入11位电话号码" maxlength='11' style="width: 200px;"></el-input>
          <span style="color:red;">{{msgMobile}}</span>
        </el-form-item>

        <el-form-item label="密码（必填）" label-width="80px">
          <el-input type="password" v-model="password" auto-complete="new-password" placeholder="请输入6-18位密码" maxlength='18' minlength="6" style="width: 200px;"></el-input> 
          <span style="color:red;">{{msgPassword}}</span> 
        </el-form-item>

        <el-form-item label-width="100px" label="设置开通权限：" class="postInfo-container-item">
          <el-select v-model="permissionIds" multiple placeholder="请选择（可多选）" @change="getPermissionOptions" track-by="value" label="label">
            <el-option
              v-for="item in conditions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogUserInfoVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdateInfo()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getNameList, getId_audit, update, modification, getId, openSchoolPcReport, closeSchoolPcReport, openSchoolManage, closeSchoolManage, querySchoolUserInfo, updateSchoolUserInfo, queryPermissions } from '@/api/highSchool'
import { getToken } from '@/utils/auth' // 验权
import Tinymce from '@/components/Tinymce'
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'list',
  components: { Tinymce },
  watch: {
    mobile(e){
      if(!(/^1[345789]\d{9}$/).test(e) && e != ''){
        this.msgMobile = '请输入的正确的手机号码'
      }else{
        this.msgMobile = ''
      }
    },
    password(e){
      if(e.indexOf(' ') >= 0){
        this.msgPassword = '不允许使用空格作为密码'
      }else if(e.trim().length != 0 && (e.trim().length < 6 || e.trim().length > 18)){
        this.msgPassword = '请输入6-18位密码'
      }else{
        this.msgPassword = ''
      }
    },
    mob(e){
      if(!(/^1[345789]\d{9}$/).test(e) && e != ''){
        this.msgMobile = '请输入的正确的手机号码'
      }else{
        this.msgMobile = ''
      }
    },
    pass(e){
      if(e.indexOf(' ') >= 0){
        this.msgPassword = '不允许使用空格作为密码'
      }else if(e.trim().length != 0 && (e.trim().length < 6 || e.trim().length > 18)){
        this.msgPassword = '请输入6-18位密码'
      }else{
        this.msgPassword = ''
      }
    }
  },
  data() {
    return {
      headers:{},
      list: [],
      total: null,
      listLoading: true,
      tableKey: 0,
      showAllDel: false,
      dateformat:'',
      listQuery: {
        title: '',
        areaId:null,
        isSchoolManage:null,
        isSchoolPcReport:null,
        permissionId:null,
        pageNo: 1,
        pageSize: 10
      },
      isSchoolManageList: [{
        id: 1,
        name: '全部',
        type: null
      }, {
        id: 2,
        name: '是',
        type: 1
      }, {
        id: 3,
        name: '否',
        type: 0
      }],
      isSchoolPcReportList: [{
        id: 1,
        name: '全部',
        type: null
      }, {
        id: 2,
        name: '是',
        type: 1
      }, {
        id: 3,
        name: '否',
        type: 0
      }],
      mob: '',
      pass: '',
      permission: [],
      dialogFormVisible: false,
      dialogUserInfoVisible: false,
      permissionId: null,
      isSchoolManage: null,
      isSchoolPcReport: null,
      dialogVisible: false,
      schoolId: null,
      mobile: '',
      password: '',
      msgMobile: '',
      msgPassword: '',
      modelId: null,
      conditions: [],
      permissionIds: []
    }
  },
  created() {
    this.getNameList()
    this.GetAreaCascadeOptions()
    this.headers = { accessToken:getToken() }
  },
  computed: {
    ...mapGetters(['areaCascadeOptions'])
  },
  mounted() {
    this.headers = { accessToken:getToken() }
    this.getPermissionOptions()
  },
  methods: {
    // 映射 Actions
    ...mapActions(['GetAreaCascadeOptions']),

    // 通过高中名称和地区模糊查询
    getNameList(){
      this.listLoading = true
      const params = {
        title: this.listQuery.title,
        areaId: this.listQuery.areaId == null ? null : this.listQuery.areaId[this.listQuery.areaId.length - 1],
        permissionId: this.listQuery.permissionId,
        isSchoolPcReport: this.listQuery.isSchoolPcReport,
        isSchoolManage: this.listQuery.isSchoolManage,
        pageNo: this.listQuery.pageNo,
        pageSize: this.listQuery.pageSize
      }
      getNameList(params).then(res => {
        if(res.code == 0){
          this.list = res.data.list
          this.total = res.data.total
          this.listQuery.pageSize = res.data.pageSize
          this.listLoading = false
        }
      }).catch(err => {})
    },
    //获得学校后台权限
    getPermissionOptions(){
      queryPermissions().then(response => {
        const { code, data } = response
        if (code == 0) {
          this.conditions = data
        }
      })
    },
    // 按条件进行筛选
    handleFilter() {
      this.listQuery.pageNo = 1
      this.listQuery.pageSize = 10
      if(this.listQuery.isSchoolPcReport == 1 || this.listQuery.isSchoolPcReport == 0){
        this.listQuery.permissionId = process.env.PERMISSION_ID
      }
      this.getNameList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getNameList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getNameList()
    },
    // 开通高中PC生涯测评系统
    handleOpenPC(row) {
      const params = {
        modelId: row.id
      }
      openSchoolPcReport(params).then(res => {
        const { code, data, message } = res
        if (code == 0) {
          this.$notify({
            title: '成功',
            message: '开通成功',
            type: 'success',
            duration: 1000
          })
          this.getNameList()
        }else{
          this.$message({
            title: '失败',
            message: message,
            type: 'error',
            duration: 2000
          })
        }
      }).catch(err => {})
    },
    // 关闭高中PC生涯测评系统
    handleClosePC(row) {
      const params = {
        modelId: row.id
      }
      closeSchoolPcReport(params).then(res => {
        const { code, data, message } = res
        if (code == 0) {
          this.$notify({
            title: '成功',
            message: '关闭成功',
            type: 'success',
            duration: 1000
          })
          this.getNameList()
        }else{
          this.$message({
            title: '失败',
            message: message,
            type: 'error',
            duration: 2000
          })
        }
      }).catch(err => {})
    },
    // 开通高中后台管理系统
    open(row) {
      this.schoolId = row.id
      this.dialogVisible = true
    },
    handleOpen() {
      if(this.mob.trim().length == 0 || this.mob.length == 0){
        this.$message({
          title: '失败',
          message: '手机号为必填项，请输入后再保存',
          type: 'error',
          duration: 2000
        })
        return
      }
      if(this.pass.trim().length == 0 || this.pass.length == 0){
        this.$message({
          title: '失败',
          message: '密码为必填项，请输入后再保存',
          type: 'error',
          duration: 2000
        })
        return
      }
      if(this.permission.length == 0){
        this.$message({
          message: '请选择开通权限',
          type: 'error',
          duration: 1000
        })
        return
      }
      const params = {
        schoolId: this.schoolId,
        mobile: this.mob,
        password: this.pass,
        permissionIds:this.permission
      }
      openSchoolManage(params).then(res => {
        const { code, data, message } = res
        if (code == 0) {
          this.$notify({
            title: '成功',
            message: '开通成功',
            type: 'success',
            duration: 1000
          })
          this.dialogVisible = false
          this.mob = ''
          this.pass = ''
          this.permission = []
          this.getNameList()
        }else{
          this.$message({
            title: '失败',
            message: message,
            type: 'error',
            duration: 2000
          })
        }
      }).catch(err => {})
    },
    // 关闭高中后台管理系统
    handleClose(row) {
      const params = {
        schoolId: row.id,
        modelId: row.userId
      }
      closeSchoolManage(params).then(res => {
        const { code, data, message } = res
        if (code == 0) {
          this.$notify({
            title: '成功',
            message: '关闭成功',
            type: 'success',
            duration: 1000
          })
          this.getNameList()
        }else{
          this.$message({
            title: '失败',
            message: message,
            type: 'error',
            duration: 2000
          })
        }
      }).catch(err => {})
    },
    //编辑用户信息
    update(row){
      this.schoolId = row.id
      this.modelId = row.userId
      querySchoolUserInfo(row.id).then(res => {
        this.dialogUserInfoVisible = true
        const { data } = res
        this.mobile = data.mobile
        this.permissionIds = data.permissionIds
      }).catch(err => {})
    },
    handleUpdateInfo(){
      if(this.mobile.trim().length == 0 || this.mobile.length == 0){
        this.$message({
          title: '失败',
          message: '手机号为必填项，请输入后再保存',
          type: 'error',
          duration: 2000
        })
        return
      }
      if(this.password.trim().length == 0 || this.password.length == 0){
        this.$message({
          title: '失败',
          message: '密码为必填项，请输入后再保存',
          type: 'error',
          duration: 2000
        })
        return
      }
      if(this.permissionIds.length == 0){
        this.$message({
          message: '请选择开通权限',
          type: 'error',
          duration: 1000
        })
        return
      }
      const params = {
        schoolId: this.schoolId,
        mobile: this.mobile,
        password: this.password,
        id: this.modelId,
        permissionIds:this.permissionIds
      }
      updateSchoolUserInfo(params).then(res => {
        const { code, data, message } = res
        if (code == 0) {
          this.$notify({
            title: '成功',
            message: '编辑成功',
            type: 'success',
            duration: 1000
          })
          this.dialogUserInfoVisible = false
          this.mobile = ''
          this.password = ''
          this.permissionIds = []
          this.getNameList()
        }else{
          this.$message({
            title: '失败',
            message: message,
            type: 'error',
            duration: 2000
          })
        }
      }).catch(err => {})
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.icon-ctx {
  width: 160px;
  height: 80px;
  overflow: hidden;
  margin: 0 auto;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.app-container {
  padding: 20px;
}
.pagination-container {
  margin-top: 30px;
}
.form{
  width: 90%;
}
.postInfo-container-item {
  float: left;
}
</style>